<?php
namespace control;
/*
*委外派工单类
*/

class outsourceSendOrderClass extends adIndexClass
{
    private const table = 'machining_send_order';
    private const page = 'outsourceSendOrder';
    private const title = '委外派工单';
    private array $typeOption = ['生产加工', '生产返工'];
    public array $stateOption = ['草稿', '待确认', '已确认'];
    private array $orderTypeOption = ['生产计划' => '生产计划单', '半成品' => '半成品加工单'];



    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow='草稿'): string
    {
        $html='';
        //生成查询表单
        $html .=
            selectMultiple(array("name" => "companyId","title" => "委外单位", "table" => "supplier",'where' => " coid = '" . self::$coid . "' and outsource = '是' order by time", 'sqlField' => 'name', 'sqlId' => 'id')).
            text(array('name' => 'orderNo', 'title' => '单据编号')) .
            select(array('name' => 'type', 'option' => $this->typeOption, 'title' => '派工单类型')) .
            text(array('name' => 'machiningOrderNo', 'title' => '关联源单')) .
            selectMultiple(array("name" => "processId", "title" => "工序", "table" => "process",'where'=>"coid = '".self::$coid."'", 'sqlField' => 'name', 'sqlId' => 'id')) .
            text(array('name' => 'code', 'title' => '产品编码')) .
            text(array('name' => 'materialName', 'title' => '产品名称')) .
            text(array("name" => "startTime", 'laydate' => ['range' => '~'], 'class' => 'width200', "title" => "计划开工日期-计划开工日期")) .
            text(array("name" => "endTime", 'laydate' => ['range' => '~'], 'class' => 'width200', "title" => "计划完工日期-计划完工日期"));
        return $this->search($html, 'menu').$this->homeJs();
    }

    public function homeJs(){
        return <<<eof
<script>
function get_list_box(formName) {
    let arr = [];
    $("[name='" + formName + "'] input[type=checkbox]:checked").each(function () {
        if ($(this).val() && $(this).val() !== 'on') {
            arr.push($(this).val());
        }
    });
    if (arr.length > 0) {
        var vals = arr.join(",");
       window.open(root+'control/adIndex.html?cla=outsourceSendOrder&fun=printEdit&listId='+vals)
    } else {
        msg('请选择需要数据');
    }
}
</script>
eof;

    }
    /*行政人事-出差记录-查询条件*/
    public function home($workFlow='草稿')
    {
        $data = [
            "id" => "all",
            "menu" => [
                "draft" => "草稿",
                "waitReport" => "待报工",
                "partReport" => "部分报工",
                "reported" => "已报工",
            ]
        ];
        $data['html'] = $this->homeForm($workFlow);
        return $this->tab($data);
    }
    /*行政人事-出差记录-查询结果*/
    public function homeSearch()
    {
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            "type" => $this->post('type'),
            "processId" => $this->post('processId'),
            "lineId" => $this->post('lineId'),
            'classify'=>'委外派工',
            'companyId'=>$this->post('companyId')
        );
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
        );

        //初始化
        $and = " and state !='已确认'";
        $mAnd = '';

        if ($this->post('machiningOrderNo')) {
            $and = " and machiningOrderId in (select id from machining_order where orderNo like '%" . $this->post('machiningOrderNo') . "%' and coid = '" . self::$coid . "')";
        }
        if ($this->post('code')) {
            $mAnd .= " and code like '%" . $this->post('code') . "%'";
        }
        if ($this->post('materialName')) {
            $mAnd .= " and name like '%" . $this->post('materialName') . "%'";
        }
        if ($mAnd) {
            $and .= " and materialId in (select id from material where coid = '" . self::$coid . "' {$mAnd})";
        }
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'), field: 'startDate');
        }
        if ($this->post('endTime')) {
            $and .= self::timeComparison($this->post('endTime'), field: 'endDate');
        }
        if ($this->post('state')) {
            $and .= " and state in ('" . implode("','", $this->post('state')) . "')";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "startDate desc,orderNo desc"));
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = array($checkAll, '单据编号', '委外单位',"加工单类型",'单据标签', "工序", "物料编码", "物料名称", "规格型号", '单位', '生产数量', '源单类型','关联源单', '计划开工日期', '计划完成日期', '单据日期', '状态');
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
                'print' => array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
                'track'=> array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=委外派工单&id=" . $array['id'] . "')"),
            );
            $machiningOrder = query('machining_order', "id = '$array[machiningOrderId]'");
            $process = query('process', "id = '$array[processId]'");
            $material = query('material', "id = '$array[materialId]'");
            $supplier = query('supplier', "id = '$array[companyId]'");
            $tags = orderTagClass::getTagName($array['id']);
            //返回本行
            $tr[] = array($this->dominate($dominate), $array['orderNo'],$supplier['name'], $array['type'],$tags, $process['name'], $material['code'], $material['name'], $material['model'], $array['unit'],
                self::lostZero($array['num'],'numPrecision'), $this->orderTypeOption[$array['orderType']],$machiningOrder['orderNo'], $array['startDate'], $array['endDate'], date('Y-m-d', strtotime($array['time'])), $array['state']);
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n
<span onclick=\"layer('" . self::page . "','batchSend',{})\" class='spanButton'>批量派工</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= " <span onclick=\"layer('" . self::page . "','batchAddTags',{})\" class='spanButton'>批量打标签</span>\n";
        }
        if ($this->power(self::page, "confirm")){
            $button.=" <span onclick=\"layer('" . self::page . "','batchConfirm',{})\" class='spanButton'>批量确认</span>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= "<span onclick=\"get_list_box('listForm')\" class='spanButton'>批量打印</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function batchSend(){
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "委外单位：" => selectMultiple(array("name" => "companyId",  "title" => "请选择", "table" => "supplier",'where' => " state ='启用' and coid = '" . self::$coid . "' and outsource = '是' order by time", 'sqlField' => 'name', 'sqlId' => 'id')),
            ),
        )));
        //返回
        return $this->layer(array("title" => "批量派工",'winFix'=>true, "height" => 200, "html" => $html, 'formTwo' => 'listForm'));
    }
    public function batchSendEdit(){
        $listId = $this->post('listId');
        $companyId = $this->post('companyId');
        if (static::is_null_array($listId)) {
            $json['warn'] = '请选择数据';
        } elseif(empty($companyId)){
            $json['warn'] = '请选择委外单位';
        }else {
            $x = 0;
            $text = '';
            $supplier = query('supplier',"id = '$companyId'");
            foreach ($listId as $id) {
                $machiningSendOrder = query(self::table, "id = '$id'");
                $warn = update(array('table' => self::table, 'field' => ['companyId' => $supplier['id']], 'where' => "id = '$id'"));
                if ($warn == '更新成功') {
                    $x++;
                    $text .= "委外派工单【{$machiningSendOrder['orderNo']}】,更新了委外单位为：{$supplier['name']}<br>";
                } else {
                    $text .= "委外派工单【{$machiningSendOrder['orderNo']}】更新委外单位失败<br>";
                }
            }
            if ($text) {
                $text = $this->control['name'] . '批量派工了委外派工单如下：' . $text;
                $this->logText(["type" => self::page, "text" => $text]);
            }
            $json['warn'] = 2;
            $_SESSION['warn'] = "批量派工了{$x}个派工单";
        }
        return json_encode($json, 320);
    }
    public function waitReport(): bool|string
    {
        $json['html'] = $this->homeForm('待报工');
        return json_encode($json, 320);
    }
    public function waitReportSearch(): bool|string
    {
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            "type" => $this->post('type'),
            "processId" => $this->post('processId'),
            "lineId" => $this->post('lineId'),
            'classify'=>'委外派工',
            'state'=>'已确认',
            'companyId'=>$this->post('companyId')
        );
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
        );

        //初始化
        $and = " and id not in (select distinct sendId from process_report where coid = '".self::$coid."')";
        $mAnd = '';

        if ($this->post('machiningOrderNo')) {
            $and = " and machiningOrderId in (select id from machining_order where orderNo like '%" . $this->post('machiningOrderNo') . "%' and coid = '" . self::$coid . "')";
        }
        if ($this->post('code')) {
            $mAnd .= " and code like '%" . $this->post('code') . "%'";
        }
        if ($this->post('materialName')) {
            $mAnd .= " and name like '%" . $this->post('materialName') . "%'";
        }
        if ($mAnd) {
            $and .= " and materialId in (select id from material where coid = '" . self::$coid . "' {$mAnd})";
        }
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'), field: 'startDate');
        }
        if ($this->post('endTime')) {
            $and .= self::timeComparison($this->post('endTime'), field: 'endDate');
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "startDate desc,orderNo desc"));
        //获取表头
        $checkAll = $this->checkAll("waitForm", "listId");
        $tr[] = array($checkAll, '单据编号','委外单位', "加工单类型",'单据标签',  "工序", "物料编码", "物料名称", "规格型号", '单位', '生产数量', '源单类型','关联源单', '计划开工日期', '计划完成日期', '单据日期', '状态');
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "report" => array("title" => "报工", "click" => "newIframe('工序报工详情','" . $this->root . "control/adIndex.html?cla=outProcessReport&fun=edit&sourceId=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
                'print' => array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
                'track'=> array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=委外派工单&id=" . $array['id'] . "')"),
            );
            $machiningOrder = query('machining_order', "id = '$array[machiningOrderId]'");
            $process = query('process', "id = '$array[processId]'");
            $material = query('material', "id = '$array[materialId]'");
            $supplier = query('supplier', "id = '$array[companyId]'");
            $tags = orderTagClass::getTagName($array['id']);
            //返回本行
            $tr[] = array($this->dominate($dominate), $array['orderNo'], $supplier['name'],$array['type'],$tags, $process['name'], $material['code'], $material['name'], $material['model'], $array['unit'],
                self::lostZero($array['num'],'numPrecision'), $this->orderTypeOption[$array['orderType']],$machiningOrder['orderNo'], $array['startDate'], $array['endDate'], date('Y-m-d', strtotime($array['time'])), $array['state']);
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= " <span onclick=\"layer('" . self::page . "','batchAddTags',{})\" class='spanButton'>批量打标签</span>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= "<span onclick=\"get_list_box('waitForm')\" class='spanButton'>批量打印</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='waitForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function partReport(){
        $json['html'] = $this->homeForm('部分报工');
        return json_encode($json, 320);
    }
    public function partReportSearch(){
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            "type" => $this->post('type'),
            "processId" => $this->post('processId'),
            "lineId" => $this->post('lineId'),
            'classify'=>'委外派工',
            'state'=>'已确认',
            'companyId'=>$this->post('companyId')
        );
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
        );

        //初始化
        $and = " and workFlow = 0 and id in (select distinct sendId from process_report where coid = '".self::$coid."')";
        $mAnd = '';

        if ($this->post('machiningOrderNo')) {
            $and = " and machiningOrderId in (select id from machining_order where orderNo like '%" . $this->post('machiningOrderNo') . "%' and coid = '" . self::$coid . "')";
        }
        if ($this->post('code')) {
            $mAnd .= " and code like '%" . $this->post('code') . "%'";
        }
        if ($this->post('materialName')) {
            $mAnd .= " and name like '%" . $this->post('materialName') . "%'";
        }
        if ($mAnd) {
            $and .= " and materialId in (select id from material where coid = '" . self::$coid . "' {$mAnd})";
        }
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'), field: 'startDate');
        }
        if ($this->post('endTime')) {
            $and .= self::timeComparison($this->post('endTime'), field: 'endDate');
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "startDate desc,orderNo desc"));
        //获取表头
        $checkAll = $this->checkAll("partReportForm", "listId");
        $tr[] = array($checkAll, '单据编号','委外单位', "加工单类型",'单据标签',  "工序", "物料编码", "物料名称", "规格型号", '单位', '生产数量', '源单类型','关联源单', '计划开工日期', '计划完成日期', '单据日期', '状态');
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "report" => array("title" => "报工", "click" => "newIframe('工序报工详情','" . $this->root . "control/adIndex.html?cla=outProcessReport&fun=edit&sourceId=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
                'print' => array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
                'track'=> array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=委外派工单&id=" . $array['id'] . "')"),
            );
            $machiningOrder = query('machining_order', "id = '$array[machiningOrderId]'");
            $process = query('process', "id = '$array[processId]'");
            $material = query('material', "id = '$array[materialId]'");
            $supplier = query('supplier', "id = '$array[companyId]'");
            $tags = orderTagClass::getTagName($array['id']);
            //返回本行
            $tr[] = array($this->dominate($dominate), $array['orderNo'],$supplier['name'], $array['type'],$tags, $process['name'], $material['code'], $material['name'], $material['model'], $array['unit'],
                self::lostZero($array['num'],'numPrecision'), $this->orderTypeOption[$array['orderType']],$machiningOrder['orderNo'], $array['startDate'], $array['endDate'], date('Y-m-d', strtotime($array['time'])), $array['state']);
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= " <span onclick=\"layer('" . self::page . "','batchAddTags',{})\" class='spanButton'>批量打标签</span>\n
                        <span onclick=\"layer('" . self::page . "','reportComplete',{})\" class='spanButton'>报工完成</span>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= "<span onclick=\"get_list_box('partReportForm')\" class='spanButton'>批量打印</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='partReportForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    public function reported(){
        $json['html'] = $this->homeForm('已报工');
        return json_encode($json, 320);
    }
    public function reportedSearch(){
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            "type" => $this->post('type'),
            "processId" => $this->post('processId'),
            "lineId" => $this->post('lineId'),
            'classify'=>'委外派工',
            'state'=>'已确认',
            'workFlow'=> 1,
            'companyId'=>$this->post('companyId')
        );
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
        );

        //初始化
        $and = "";
        $mAnd = '';

        if ($this->post('machiningOrderNo')) {
            $and = " and machiningOrderId in (select id from machining_order where orderNo like '%" . $this->post('machiningOrderNo') . "%' and coid = '" . self::$coid . "')";
        }
        if ($this->post('code')) {
            $mAnd .= " and code like '%" . $this->post('code') . "%'";
        }
        if ($this->post('materialName')) {
            $mAnd .= " and name like '%" . $this->post('materialName') . "%'";
        }
        if ($mAnd) {
            $and .= " and materialId in (select id from material where coid = '" . self::$coid . "' {$mAnd})";
        }
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'), field: 'startDate');
        }
        if ($this->post('endTime')) {
            $and .= self::timeComparison($this->post('endTime'), field: 'endDate');
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "startDate desc,orderNo desc"));
        //获取表头
        $checkAll = $this->checkAll("reportedForm", "listId");
        $tr[] = array($checkAll, '单据编号', '委外单位',"加工单类型",'单据标签',  "工序", "物料编码", "物料名称", "规格型号", '单位', '生产数量', '源单类型','关联源单', '计划开工日期', '计划完成日期', '单据日期', '状态');
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
                'print' => array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"),
                'track'=> array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=委外派工单&id=" . $array['id'] . "')"),
            );

            $machiningOrder = query('machining_order', "id = '$array[machiningOrderId]'");
            $process = query('process', "id = '$array[processId]'");
            $material = query('material', "id = '$array[materialId]'");
            $supplier = query('supplier', "id = '$array[companyId]'");
            $tags = orderTagClass::getTagName($array['id']);
            //返回本行
            $tr[] = array($this->dominate($dominate), $array['orderNo'],$supplier['name'], $array['type'],$tags,  $process['name'], $material['code'], $material['name'], $material['model'], $array['unit'],
                self::lostZero($array['num'],'numPrecision'), $this->orderTypeOption[$array['orderType']],$machiningOrder['orderNo'], $array['startDate'], $array['endDate'], date('Y-m-d', strtotime($array['time'])), $array['state']);
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= " <span onclick=\"layer('" . self::page . "','batchAddTags',{})\" class='spanButton'>批量打标签</span>\n
                        <span onclick=\"layer('" . self::page . "','cancelReport',{})\" class='spanButton'>取消完成</span>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= "<span onclick=\"get_list_box('reportedForm')\" class='spanButton'>批量打印</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='reportedForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    public function reportComplete(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must."提示："=>'是否确认将所选数据标记为报工已完成？'
            ),
        )));
        //返回
        return $this->layer(array("title" => "报工完成", "height" => 165, "width" => 600, "html" => $html, 'formTwo' => 'partReportForm'));
    }

    public function reportCompleteEdit(): bool|string
    {
        $listId = $this->post('listId');
        if (static::is_null_array($listId)) {
            $json['warn'] = '请选择数据';
        }else {
            $x = 0;
            $text = '';
            foreach ($listId as $id) {
                $info = query(self::table,"id = '$id'");
                $warn = update(array('table' => self::table, 'field' => ['workFlow' => 1], 'where' => "id = '$id'"));
                if ($warn == '更新成功') {
                    $x++;
                    $text .= "委外派工单【{$info['orderNo']}】更新为报工已完成<br>";
                } else {
                    $text .= "委外派工单【{$info['orderNo']}】更新为报工已完成失败<br>";
                    break;
                }
            }
            if ($text){
                $text = $this->control['name'] . '批量标记派工单报工已完成如下：' . $text;
            }
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
            $json['href'] = root.'control/adIndex.html?cla='.self::page.'&fun=home&menu=partReport';
            $_SESSION['warn'] = "成功操作了{$x}条数据";
        }
        return json_encode($json, 320);
    }
    public function cancelReport(){
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must."提示："=>'是否确认取消将所选数据的报工已完成？'
            ),
        )));
        //返回
        return $this->layer(array("title" => "取消报工完成", "height" => 165, "width" => 600, "html" => $html, 'formTwo' => 'reportedForm'));
    }
    public function cancelReportEdit(){
        $listId = $this->post('listId');
        if (static::is_null_array($listId)) {
            $json['warn'] = '请选择数据';
        }else {
            $x = 0;
            $text = '';
            foreach ($listId as $id) {
                $info = query(self::table,"id = '$id'");
                $warn = update(array('table' => self::table, 'field' => ['workFlow' => 0], 'where' => "id = '$id'"));
                if ($warn == '更新成功') {
                    $x++;
                    $text .= "委外派工单【{$info['orderNo']}】取消报工已完成<br>";
                } else {
                    $text .= "委外派工单【{$info['orderNo']}】取消报工已完成失败<br>";
                    break;
                }
            }
            if ($text){
                $text = $this->control['name'] . '批量取消派工单报工已完成如下：' . $text;
            }
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
            $json['href'] = root.'control/adIndex.html?cla='.self::page.'&fun=home&menu=reported';
            $_SESSION['warn'] = "成功操作了{$x}条数据";
        }
        return json_encode($json, 320);
    }
    public function batchConfirm(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否批量确认所选的委外派工单？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "提示", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }

    public function batchConfirmEdit(): bool|string
    {
        $listId = $this->post('listId');
        if (static::is_null_array($listId)) {
            $json['warn'] = '请选择数据';
        } else {
            $x = 0;
            $text = '';
            $this->startTrans();
            $json['warn'] = '';
            foreach ($listId as $id) {
                $outsourceSendOrder = query(self::table, "id = '$id'");
                if (empty($outsourceSendOrder['num']) || $outsourceSendOrder['num'] <= 0) {
                    $json['warn'] = "派工单【{$outsourceSendOrder['orderNo']}】的生产数量为0";
                    break;
                }elseif(empty($outsourceSendOrder['companyId'])){
                    $json['warn'] = "派工单【{$outsourceSendOrder['orderNo']}】未选择委外单位";
                    break;
                }
                $warn = update(array('table' => self::table, 'field' => ['state' => '已确认','checkId'=>self::$stid,'confirmTime'=>$this->time], 'where' => "id = '$id'"));
                if ($warn == '更新成功') {
                    $x++;
                    $text .= "委外派工单【{$outsourceSendOrder['orderNo']}】,确认成功<br>";
                    auditClass::operateRecord($id,'委外派工单','确认');
                } else {
                    $json['warn'] = "派工单【{$outsourceSendOrder['orderNo']}】确认失败";
                    break;
                }
            }
            if (empty($json['warn'])) {
                $this->commitTrans();
                $text = $this->control['name'] . '批量确认了委外派工单如下：' . $text;
                $this->logText(["type" => self::page, "text" => $text]);
                $json['warn'] = 2;
                $_SESSION['warn'] = "成功确认了{$x}条数据";
            } else {
                $this->rollback();
            }

        }
        return json_encode($json, 320);
    }

    /**
     * 编辑
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        $machining_order = query('machining_order', "id = '$info[machiningOrderId]'");
        $machining_ordeMx = query('machining_order_mx', "id = '$info[machiningOrderMxId]'");
        $materialName = $machining_order['id'] ? materialClass::getName($machining_ordeMx['materialId']) : '';
        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                array(
                    must . "源单类型：" => radio(array('name' => 'orderType', 'value' => $this->orderTypeOption, 'checked' => $info['orderType'] ?:'生产计划'))
                ),
                array(
                    must."委外单位："=>selectMultiple(array("name" => "companyId", 'value' => $info['companyId'], "title" => "请选择", "table" => "supplier",'where' => " state ='启用' and coid = '" . self::$coid . "' and outsource = '是' order by time", 'sqlField' => 'name', 'sqlId' => 'id'))
                ),
                array(
                    must . "关联源单：" => "<span id='machiningOrderNo'>" . $machining_order['orderNo'] . "</span><span style='margin-left: 5px' onclick=\"layer('{$this->get('cla')}','addOrder',$('form[name=outsourceSendOrderEditForm]').serialize())\" class='del-row-button' >选择</span>"
                ),
                array(
                    "派工单类型：" => "<span id='sendType'>{$info['type']}</span>",
                ),
                array(
                    "物料：" => "<span id='material'>{$materialName}</span>" . hidden(array('name' => 'machiningOrderMxId', 'value' => $machining_ordeMx['id'])),
                ),

                array(
                    '单位：' => "<span id='unit'>{$info['unit']}</span>"
                ),
                array(
                    must . "生产数量：" => text(array("name" => "num", 'other' => self::digitalFiltering('numPrecision'), "value" => self::lostZero($info['num'],'numPrecision'))),
                ),
                array(
                    must . "工序：" => "<div id='process'>" . selectMultiple(array("name" => "processId", 'value' => $info['processId'], "title" => "工序", "table" => "process", 'where' => " state ='启用' and id in (select processId from routing_detail where orderId = '$machining_ordeMx[routingId]')", 'sqlField' => 'name', 'sqlId' => 'id')) . "</div>"
                ),
                array(
                    "计划开工时间：" => text(array("name" => "startDate", 'laydate' => [], "value" => self::null($info['startDate'], false))),
                ),
                array(
                    "计划完工时间：" => text(array("name" => "endDate", 'laydate' => [], "value" => self::null($info['endDate'], false))),
                ),
                array(
                    "备注：" => textarea(array("name" => "text", "value" => $info['text'])),
                ),
            ],
            'hidden' => hidden(array('name' => 'id', 'value' => $id)),
            'button' => "<button class=\"button left-bottom\" onclick=\"subForm('{$this->get('cla')}EditForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')\">保存</button>",
        ]);
        //返回
        return $this->tab($data) . $this->js();

    }

    public function js(): string
    {
        return <<<efo
<script>
          //选择生产产品
    function addMaterial(){
             $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addOrderEdit',$("form[name='mxForm']").serialize(),function(res) {
                 if (res.warn ==2){
                   $('#outsourceSendOrderAddOrder').hide()
                   $("#unit").html(res.data.unit);
                   $("#machiningOrderNo").html(res.data.orderNo);
                   $("#sendType").html(res.data.type);
                   $("#material").html(res.data.materialName);
                   $("#process").empty().append(res.data.process);
                   $("[name='machiningOrderMxId']").val(res.data.id);
                   $("[name='num']").val(res.data.num);
                   $("[name='startDate']").val(res.data.startDate);
                   $("[name='endDate']").val(res.data.endDate);
                 }else{
                     msg(res.warn);
                 }
            },'json');
    }
</script>
efo;

    }

    /**
     * 从生产计划中选择
     * @return bool|string
     */
    public function addOrder(): bool|string
    {
        $html =
            text(array("name" => "orderNo", "title" => "生产计划单/半成品加工单号")) .
            text(array("name" => "code", "title" => "产品编码")) .
            text(array("name" => "materialName", "title" => "产品名称")) .
            text(array("name" => "model", "title" => "规格型号")) .
            hidden(array('name' => 'orderType', 'value' => $this->post('orderType'))) .
            hidden(array('name' => 'id', 'value' => $this->post('id')));
        $button = "<input style='margin-left: 5px' onclick=\"addMaterial()\" type='button' class='searchSub' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button));
    }

    /**
     * 从生产计划中选择
     * @return bool|string
     */
    public function addOrderSearch(): bool|string
    {
        $where = " a.coid='" . self::$coid . "'";
        $and = " and b.isClose = 0";
        $like = [
            'b.orderNo' => $this->post('orderNo'),
            'c.name' => $this->post('materialName'),
            'c.code' => $this->post('code'),
            'c.model' => $this->post('model'),
        ];
        $equal = [
            'b.state' => '已确认',
            'b.lineId' => $this->post('lineId'),
            'b.orderType' => $this->post('orderType')
        ];

        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "machining_order_mx as a join machining_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'field' => "a.*,c.name,c.code,c.model,c.unit,b.orderNo,b.lineId",
            "where" => $where,
            'pageNum' => 50,
            "order" => "b.recordDate desc,a.`list` asc",
        ]);
        //获取表头
        $tr[] = ['', '生产计划单/半成品加工单',  '产品编码', '产品名称', '规格型号', '单位', '计划数量'];
        //获取记录
        foreach ($page['array'] as $array) {
            $tr[] = array(
                "<input name='mxId' type='radio' value='{$array['id']}'>",
                $array['orderNo'],
                $array['code'],
                $array['name'],
                $array['model'],
                $array['unit'],
                self::lostZero($array['num'],'numPrecision'),
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='mxForm'>" .
                hidden(array('name' => 'id', 'value' => $this->post('id'))) .
                $this->tableMany(array("tr" => $tr)) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 从生产计划中选择
     */
    public function addOrderEdit(): bool|string
    {
        $mxId = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxId)) {
            $json['warn'] = '请选择生产计划单产品';
        } else {
            $json['warn'] = 2;
            $machiningOrderMx = query('machining_order_mx', "id = '$mxId'");
            $machiningOrder = query('machining_order', "id = '$machiningOrderMx[orderId]'");
            $material = query('material', " id = '$machiningOrderMx[materialId]'");
            //已派工数量
            $num = find(array('table' => self::table, 'where' => "machiningOrderMxId = '$machiningOrderMx[id]' and id !='" . $this->post('id') . "'", 'sum' => "num"));
            $json['data'] = [
                'id' => $machiningOrderMx['id'],
                'unit' => $machiningOrderMx['unit'],
                'type' => $machiningOrder['type'],
                'orderNo' => $machiningOrder['orderNo'],
                'startDate' => $machiningOrder['startDate'],
                'endDate' => $machiningOrder['endDate'],
                'num' => ($machiningOrderMx['num'] - $num) <= 0 ? 0 : self::formattingFigure($machiningOrderMx['num'] - $num,'numPrecision'),
                'materialName' => $material['code'] . '-' . $material['name'] . '-' . $material['model'],
                'process' => selectMultiple(array("name" => "processId", "title" => "工序", "table" => "process", 'where' => " state ='启用' and id in (select processId from routing_detail where orderId = '$machiningOrderMx[routingId]' and isOut = '是')", 'sqlField' => 'name', 'sqlId' => 'id')),
            ];

        }
        return json_encode($json, 320);
    }


    /*编辑*/
    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        //赋值
        $field = array(
            "startDate" => $this->post('startDate'),
            "companyId" => $this->post('companyId'),
            "endDate" => $this->post('endDate'),
            "machiningOrderMxId" => $this->post('machiningOrderMxId'),//备注
            "processId" => $this->post('processId'),
            "num" => $this->post('num')?self::formattingFigure($this->post('num'),'numPrecision'):'',
            "text" => $this->post('text'),
        );
        $annotation = [
            "companyId" => '委外单位',
            "machiningOrderMxId" => '生产计划',
            "processId" => '工序',
            "num" => '生产数量',
        ];
        $rules = [
            "companyId" => 'required',
            "machiningOrderMxId" => 'required',
            "processId" => 'required',
            "num" => 'required|numeric',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "权限不足";
        } elseif ($info['state'] == '已确认') {
            $json['warn'] = '此委外派工单已确认，不能编辑';
        } elseif($field['num'] <=0){
            $json['warn'] = '生产数量不能小于0';
        }elseif (!empty($field['startDate']) && !empty($field['endDate']) && strtotime($field['endDate']) < strtotime($field['startDate'])) {
            $json['warn'] = '计划完工时间不能小于计划开工时间';
        } else {
            $machiningOrderMx = query('machining_order_mx', "id = '$field[machiningOrderMxId]'");
            $machiningOrder = query('machining_order', "id = '$machiningOrderMx[orderId]'");
            $field['classify'] ='委外派工';
            $field['type'] = $machiningOrder['type'];
            $field['unit'] = $machiningOrderMx['unit'];
            $field['orderType'] = $machiningOrder['orderType'];
            $field['machiningOrderId'] = $machiningOrder['id'];
            $field['materialId'] = $machiningOrderMx['materialId'];
            $field['routingId'] = $machiningOrderMx['routingId'];
            $routingDetail = query('routing_detail',"orderId = '$field[routingId]' and processId ='$field[processId]' order by list");
            $field['routingMxId'] = $routingDetail['id'];
            $field['classify'] = $routingDetail['isOut']=='是'?'委外派工':'生产派工';
            if (empty($info['id'])) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'SCPG' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => " and coid = '".self::$coid."'",
                ],$field);
                $field = array_merge($field, array("id" => $id, 'recordDate'=>$this->date, 'coid' => self::$coid, 'orderNo' => $userNo, 'state' => '草稿', 'stid' => $this->control['stid']));
                $json['warn'] = insert(array("table" => self::table, "field" => $field));
            } else {
                $json['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
            }
            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                if ($json['warn'] == '新增成功') {
                    auditClass::operateRecord($id,'委外派工单','新建');
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "ID：" . $id;
                $this->logText(array("type" => self::page, "text" => $text));
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }

        $json['href'] = root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $id;
        resp:
        return json_encode($json, 320);
    }


    /*出差详情*/
    public function detail(): string
    {
        //定义参数
        if (empty($this->get('id'))) {
            $html = '未找到此' . self::title;
        } else {
            $info = query(self::table, " id = '" . $this->get('id') . "' ");
            if (empty($info['id'])) {
                $html = "未找到此记录";
            } else {
                //菜单
                $data = array(
                    "id" => $info['id'],
                );

                $button = [];
                if ($info['state'] == '草稿') {
                    //按钮
                    $button[] = [
                        "name" => "提交",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                }
                if ($info['state'] != '已确认') {
                    if ($this->power(self::page, "edit")) {
                        //按钮
                        $button[] = [
                            "name" => "编辑",
                            "type" => "顶部页卡",
                            "title" => "编辑用户",
                            "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],

                        ];
                    }
                    if ($this->power(self::page, "del")) {
                        //按钮
                        $button[] = [
                            "name" => "删除",
                            "type" => "弹出层",
                            "cla" => $this->get('cla'),
                            "fun" => "operate",
                            "post" => ["act" => 'del', "id" => $info['id']],
                        ];
                    }
                }

                if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                    $button[] = [
                        "name" => "确认",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'confirm', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                }
                if ($this->power(self::page, "confirm") && $info['state'] == '已确认') {
                    if (!$info['workFlow'] && !$info['isClose']){
                        $button[] = [
                            "name" => "报工",
                            "type" => "顶部页卡",
                            "title" => "委外报工",
                            "url" => $this->root . "control/adIndex.html?cla=outProcessReport&fun=edit&sourceId=" . $info['id'],
                            'style' => 'li-btn-blue-bg',
                        ];
                    }
                    if (!$info['isClose']){
                        $button[] = [
                            "name" => "撤回",
                            "type" => "弹出层",
                            "cla" => $this->get('cla'),
                            "fun" => "operate",
                            "post" => ["act" => 'cancel', "id" => $info['id']],
                        ];
                    }
                }
                if ($this->power(self::page, "edit") && $info['state'] == '已确认') {
                    //按钮
                    $isClose = $info['isClose'] == 1 ? 0 : 1;
                    $name = $info['isClose'] == 1 ? '开启' : '关闭';
                    $button[] = [
                        "name" => $name,
                        "type" => "点击事件",
                        "fun" => "layer('" . self::page . "','stateSwitch',{id:'" . $info['id'] . "',type:'{$isClose}'})",
                    ];
                }
                $button[] = [
                    "name" => "单据追踪",
                    "type" => "顶部页卡",
                    "title" => "单据追踪",
                    "url" => $this->root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=委外派工单&id=" . $info['id'],
                ];
                //操作记录
                $button[] = self::operateLogBut($info['id']);

                $machiningOrder = query('machining_order', "id = '$info[machiningOrderId]'");
                $supplier = query('supplier', "id = '$info[companyId]'");
                $process = query('process', "id = '$info[processId]'");
                //生成表单
                $data['html'] = $this->tableShow(array(
                    "button" => $button,
                    '基本信息' => array(
                        array(
                            "派工单类型" => $info['orderNo'],
                            "关联生产计划单号" => $machiningOrder['orderNo'],
                            '委外单位'=>$supplier['name'],
                             "物料" => materialClass::getName($info['materialId']),
                        ),
                        array(
                            "单位" => $info['unit'],
                            "生产数量" => self::lostZero($info['num'],'numPrecision'),
                            "工序" => $process['name'],
                            "计划开始时间" => $info['startDate'],
                        ),
                        array(
                            "计划下线时间" => $info['endDate'],
                        ),
                        array(
                            "备注" => pre($info['text']),
                        ),
                    ),
                    '系统信息' => array(
                        array(
                            "创建人" => self::findStaff($info['stid']),
                            "创建时间" => $info['time'],
                            "确认时间" => self::null($info['confirmTime']),
                            "状态" => $info['state']
                        )
                    )
                ));
                //生成页面
                $html = $this->tab($data);
            }
        }
        //返回
        return $html;
    }
    /**
     * 启用/停用
     */
    public function stateSwitch(): bool|string
    {
        $isClose = $this->post('type');
        //生成表单
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    "提示：" => "是否确认" . ($isClose == 1 ? '关闭' : '开启') . "此订单？",
                ),
            ), 'hidden' => hidden(array('name' => 'type', 'value' => $isClose)),
        ));
        //返回
        return $this->layer(array("title" => "订单状态", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 启用/停用
     */
    public function stateSwitchEdit(): bool|string
    {
        $idArr = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        $isClose = $this->post('type');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = "请选择数据";
        } else {
            $field = [
                'isClose' => $isClose,
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $type = $isClose == 1 ? '关闭' : '开启';
                foreach ($idArr as $id) {
                    auditingFollow(array(
                        "type" => "委外派工单",
                        "typeId" => $id,
                        "text" => "【{$this->control['name']}】" . $type,
                        'job' => self::findStaffDepartment(self::$stid) . '-' . $this->controlJob['name'],
                        'staffName' => $this->control['name'],
                    ));
                }
                //添加日志
                $text = $this->control['name'] . $type . "了" . self::title . "， id：【" . implode(",", $idArr) . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $type . '成功';
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }
    /**
     * 样式
     * @return string
     */
    public function style(): string
    {
        return <<<eof
<style>
.stateBlock{margin-top: 0}
.stateBlock ul li{padding: 2px 10px}
.footer-ul-parent{float: right;margin-right: 10px}
.table-top-title{height: 30px;line-height: 30px;font-size: 14px;margin-top: 20px;}
.table-top-title>ul{display: flex;flex-direction: row;padding: 2px 5px}
.table-top-title>ul>li{flex:1}
</style>
eof;

    }

    public function printEdit(){
        $listArr = explode(',', $this->get('listId'));
        $content = '';
        foreach ($listArr as $id) {
            $info = query(self::table, " id = '$id'");
            $material = query('material', "id = '$info[materialId]'");
            $company = query('company', "coid = '" . self::$coid . "'");//公司名称
            $process = query('process', "id = '$info[processId]'");
            $supplier = query('supplier', "id = '$info[companyId]'");
            //二维码
            $url = root . 'pay/wxpay/wxScanPng.php?url=' . urlencode("source=machining_send_order&id=" . $info['id']);
            $machiningOrder = query('machining_order',"id = '$info[machiningOrderId]'");
            $sourceOrderType = $machiningOrder['orderType']=='生产计划'?'生产计划单':'半成品加工单';
            $content .= "
<div data-op-type='new-page'></div>
                 <div>
                      <div class='printTitle' style='font-weight: bold;position: relative'>{$company['name']} <div style='position: absolute;font-weight: normal;right: 10px;top: 0;font-size: 14px'>{$info['orderNo']}</div></div>
                      <div class='printSubTitle'>委外派工单</div>
                 </div>
                 <div class='table-top-title'>
                     <ul>
                        <li>委外单位：{$supplier['name']}</li><li>工序：{$process['name']}</li>
                     </ul>
                      <ul>
                         <li>计划开工：{$info['startDate']}</li><li>计划完工：{$info['endDate']}</li>
                     </ul>
                      <ul>
                        <li>&nbsp;</li>
                     </ul>
                       <ul>
                        <li style='font-weight: bold'>产品：{$material['code']}-{$material['name']}</li>
                     </ul>
                     <ul>
                       <li>规格型号：{$material['model']}</li><li>数量：".self::lostZero($info['num'],'numPrecision')."</li>
                    </ul>
                     <ul> <li>源单类型：{$sourceOrderType}</li><li>关联源单：{$machiningOrder['orderNo']}</li></ul>
                    <ul> <li>备注：{$info['text']}</li></ul>
                    
                      <div style='margin-top: 10px'>
                           <img alt='二维码' style='width: 100px;vertical-align: top' src='$url'>
                           <div class='footer-ul-parent'>
                           <ul class='footer-ul'>
                               <li>打印时间：" . date('Y/m/d H:i') . "</li>
                               <li>制单人：" . self::findStaff($info['stid']) . "</li>
                               <li></li>
                           </ul>
                           </div>
                         </div>
                 </div>
            ";
        }
        $html = <<<eof
                    <div id="content-box" style="display: none">
                        
                    <!--    <div data-op-type="pendants">&lt;!&ndash; 定义页面部件（页眉/页脚/书签/水印背景等） &ndash;&gt;-->
                    <!--        <div class='pendant-title'>实发工资表</div>-->
                    <!--    </div>-->
                       {$content}
                    </div>
                 
eof;
        $html .= $this->style();
        $print = new printClass();

        return $print->showPrint($html,'landscape',['pageSize'=>'A5']);
    }
    /**
     * 打印
     */
    public function printPage(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        $material = query('material', "id = '$info[materialId]'");
        $company = query('company', "coid = '" . self::$coid . "'");//公司名称
        $process = query('process', "id = '$info[processId]'");
        $supplier = query('supplier', "id = '$info[companyId]'");
        $machiningOrder = query('machining_order',"id = '$info[machiningOrderId]'");
        $sourceOrderType = $machiningOrder['orderType']=='生产计划'?'生产计划单':'半成品加工单';
        //二维码
        $url = root . 'pay/wxpay/wxScanPng.php?url=' . urlencode("source=machining_send_order&id=" . $info['id']);

        $divHtml = "
                 <div>
                      <div class='printTitle' style='font-weight: bold;position: relative'>{$company['name']} <div style='position: absolute;font-weight: normal;right: 10px;top: 0;font-size: 14px'>{$info['orderNo']}</div></div>
                      <div class='printSubTitle'>委外派工单</div>
                 </div>
                 <div class='table-top-title'>
                     <ul>
                        <li>委外单位：{$supplier['name']}</li><li>工序：{$process['name']}</li>
                     </ul>
                      <ul>
                         <li>计划开工：{$info['startDate']}</li><li>计划完工：{$info['endDate']}</li>
                     </ul>
                     <ul>
                        <li>&nbsp;</li>
                     </ul>
                       <ul>
                        <li style='font-weight: bold'>产品：{$material['code']}-{$material['name']}</li>
                     </ul>
                     <ul>
                       <li>规格型号：{$material['model']}</li><li>数量：".self::lostZero($info['num'],'numPrecision')."</li>
                    </ul>
                     <ul> <li>源单类型：{$sourceOrderType}</li><li>关联源单：{$machiningOrder['orderNo']}</li></ul>
                    <ul> <li>备注：{$info['text']}</li></ul>
                    
                      <div style='margin-top: 10px'>
                           <img alt='二维码' style='width: 100px;vertical-align: top' src='$url'>
                           <div class='footer-ul-parent'>
                           <ul class='footer-ul'>
                               <li>打印时间：" . date('Y/m/d H:i') . "</li>
                               <li>制单人：" . self::findStaff($info['stid']) . "</li>
                               <li></li>
                           </ul>
                           </div>
                         </div>
                 </div>
            ";
        $html = <<<eof
                    <div id="content-box" style="display: none">
                        <div data-op-type='new-page'></div>
                    <!--    <div data-op-type="pendants">&lt;!&ndash; 定义页面部件（页眉/页脚/书签/水印背景等） &ndash;&gt;-->
                    <!--        <div class='pendant-title'>实发工资表</div>-->
                    <!--    </div>-->
                       {$divHtml}
                    </div>
                 
eof;
        $html .= $this->style();
        $print = new printClass();

        return $print->showPrint($html,'landscape',['pageSize'=>'A5']);
    }

    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time
        ];

        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此' . self::title;
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此' . self::title . '不是待确认状态，不能确认';
        }else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                //生成出库单
                auditClass::operateRecord($info['id'],'委外派工单','确认');
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '确认成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId' => '',
            'confirmTime' => ''
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此委外派工单';
        } elseif ($info['state'] != '已确认') {
            $json['warn'] = '此委外派工单不是已确认状态，无需撤回';
        } elseif (static::total(array('table' => 'process_report', "where" => "sendId = '$info[id]' and coid = '" . self::$coid . "'")) > 0) {
            $json['warn'] = '此委外派工单已关联有工序报工的单据，不能撤回';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditClass::operateRecord($info['id'],'委外派工单','撤回');
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '撤回成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此委外派工单';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此委外派工单不是草稿状态，不能提交';
        } elseif(empty($info['companyId'])){
            $json['warn'] = '请选择委外单位';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditClass::operateRecord($info['id'],'委外派工单','提交');
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '提交成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此' . self::title . '，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此' . self::title . '？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此' . self::title . '？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 批量添加标签
     */
    public function batchAddTags(): bool|string
    {
        $label_group = find(array('table' => 'tag', 'where' => "type=2 and coid = '" . self::$coid . "' order by time asc"));
        $group_li = '';
        foreach ($label_group['array'] as $array) {
            $group_li .= "<li>{$array['name']}</li><li>";
            $detail_ul = <<<eof
<ul class="label-content-sec-ul client-level">
eof;
            $label_detail = find(array('table' => 'tag_detail', 'where' => "orderId = '$array[id]' order by list asc"));
            foreach ($label_detail['array'] as $value) {
                $detail_ul .= "<li class='background-color-gray' data-id='{$value['id']}'>{$value['name']}</li>";
            }
            $group_li .= "{$detail_ul}<input name='tagMxId[]' type='hidden' value=''></ul></li>";
        }

        $html = <<<efo
<form name="labelForm">
<div class="label-content">
<ul>
     {$group_li}
</ul>
</div>
<div class="label-footer">
     已选<span id="label-num">0</span>个<span class="del-row-button" id="reset" style="margin-left: 20px">重置</span>
     <span class="spanButton" onclick="$('#outsourceSendOrderBatchAddTags').hide()" style="float: right">取消</span>
     <span class="spanButton li-btn-blue-bg" onclick="confirm_batch()" style="float: right">确认</span>
</div>
</form>
<style>
.label-content{
   margin: 10px 20px;height: 570px;border-bottom: 2px dashed rgb(215, 215, 215);
}
.label-content-sec-ul li {
  float: left;margin: 10px 5px;text-align: center;cursor: pointer;
}
.background-color-gray{
  margin-left: 0;
}
.label-content>ul>li{
  display: flex;
}
.label-content>ul>li:nth-child(2n+1){
  padding-left: 5px;
  margin-top: 5px;
}
.label-footer{
  height: 50px;
  line-height: 50px;
  margin: 0 20px;
}
</style>
<script>
function confirm_batch(){
     let serialize = $("[name='labelForm']").serialize();
     serialize+='&'+$("[name='listForm']").serialize();
    $('#outsourceSendOrderBatchAddTags').hide()
     $.post(root+'control/adIndex.html?cla=outsourceSendOrder&fun=batchAddTagsEdit', serialize, function (data) {
         if (data.warn == 2) {
            if (data.href) {
              window.location.href = data.href;
            } else {
              window.location.reload();
            }
          } else {
            warn(data.warn);
          }
    }, "json");
}
//计算标签数量
 function set_label_num(){
    let num =  $(".label-content-sec-ul .background-color-blue").length;
    $("#label-num").html(num);
 }
 //点击标签
 $(".label-content-sec-ul li").on('click',function() {
     let parent = $(this).parent();
     if ($(this).hasClass('background-color-blue')){
          parent.find("li").removeClass('background-color-blue');
          $(this).siblings("input[name='tagMxId[]']").val('');
     }else{
         parent.find("li").removeClass('background-color-blue');
         $(this).addClass('background-color-blue');
         let id = $(this).data('id');
         $(this).siblings("input[name='tagMxId[]']").val(id);
     }
   
     set_label_num();
 })
 //重置标签
 $("#reset").on('click',function (){
     $(".label-content-sec-ul").find("li").removeClass('background-color-blue');
     $(".label-content-sec-ul").find("input[type='hidden']").val('');
     set_label_num();
 })
</script>
efo;

        return $this->layer(array("title" => "批量添加标签", "height" => 700, "width" => 900, "html" => $html));
    }

    /**
     * 批量添加标签编辑
     */
    public function batchAddTagsEdit(): bool|string
    {
        $listId = $this->post('listId');
        $tagMxId = $this->post('tagMxId');//标签ID
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (empty($listId) || !is_array($listId)) {
            $json['warn'] = '您还没有选择单据';
        } elseif (empty($tagMxId) || !is_array($tagMxId)) {
            $json['warn'] = '您还没有选择标签';
        } else {
            $x = 0;
            $text = '';
            foreach ($listId as $id) {
                $outsourceSendOrder = query(self::table, "id = '$id'");
                $x++;
                $tagsText = '';
                //添加标签
                $kehu_label_id = [];
                foreach ($tagMxId as $tagsId) {
                    $tags_detail = query('tag_detail', "id = '$tagsId'");
                    if ($tags_detail['id']){
                        $kehu_label = query('kehu_label', "targetId = '$outsourceSendOrder[id]' and tag_detail_id = '$tagsId'");
                        $tags = query('tag', "id = '$tags_detail[orderId]'");
                        $tagsText .= $tags_detail['name'] . ',';
                        if (empty($kehu_label['id'])) {
                            $mid = self::getId();
                            $kehu_label_id[] = $mid;
                            static::insert(array(
                                'table' => 'kehu_label',
                                'field' => [
                                    'id' => $mid,
                                    'coid' => self::$coid,
                                    'targetId' => $outsourceSendOrder['id'],
                                    'tag_detail_id' => $tagsId,
                                    'tagId' => $tags['id'],
                                    'type' => 2,
                                ]
                            ));
                        } else {
                            $kehu_label_id[] = $kehu_label['id'];
                        }
                    }
                }
                //删除无效关联的标签
                delete(array('table' => 'kehu_label', 'where' => "id not in ('" . implode("','", $kehu_label_id) . "') and targetId = '$outsourceSendOrder[id]'"));
                update(array('table' => self::table, 'field' => ['tags' => $tagsText], 'where' => "id = '$outsourceSendOrder[id]'"));
                $text .= "委外派工单【{$outsourceSendOrder['orderNo']}】添加了标签{$tagsText}<br>";
            }
            $this->logText(["type" => self::page, "text" => $this->control['name'] . "批量给委外派工单添加标签：" . $text]);
            $json['warn'] = 2;
            $_SESSION['warn'] = '成功给' . $x . '个委外派工单添加了标签';

        }
        return json_encode($json, 320);
    }

}
